package com.demo.villageresidence.controller;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.villageresidence.dto.AdminDTO;
import com.demo.villageresidence.pojo.Admin;
import com.demo.villageresidence.dto.Result;
import com.demo.villageresidence.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public Map<String,Object> login(@RequestBody AdminDTO adminDTO) {
        // 登录功能
        return adminService.login(adminDTO);
    }

    @GetMapping("getAllAdmin")
    public Result getAllAdmin() {
        return adminService.getAllAdmin();
    }

    @GetMapping("getAdminPage")
    public Result getAdminPage(@RequestParam(value = "current", defaultValue = "1") Integer current,
                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<Admin> page = adminService.query().page(new Page<>(current, pageSize));
        List<Admin> records = page.getRecords();

        long total = page.getTotal();

        return Result.ok(records, total);

    }

    @PostMapping("addAdmin")
    public Result addAdmin(@RequestBody Admin admin) {
        // 判断输入的账号（手机号）是否已经存在
        Admin adminPhone = adminService.query().eq("admin_phone", admin.getAdminPhone()).one();
        if (adminPhone != null) {
            return Result.fail("该手机号已经注册");
        }
        admin.setIsDelete(0);
        // 对密码进行BCrypt加密
        String adminPassword = BCrypt.hashpw(admin.getAdminPassword());
        admin.setAdminPassword(adminPassword);
        adminService.save(admin);
        return Result.ok(admin.getAdminId());
    }

}
